package com.sos.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author 港某人
 * @date 2021/3/20 13:22
 */
public class TokenUtil {

    public static boolean isTokenOutTime(DecodedJWT decode) {
        Date expiresAt = decode.getExpiresAt();
        long time = expiresAt.getTime();
        return time < System.currentTimeMillis();
    }

    public static HttpServletRequest getRequest() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes != null) {
            return servletRequestAttributes.getRequest();
        }
        return null;
    }

    public static String decryptToken(String token, String type) {
        DecodedJWT decode = null;
        try {
            decode = JWT.decode(token);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (decode != null && !isTokenOutTime(decode)) {
            return decode.getClaim(type).asString();
        }
        return null;
    }

    public static String getDoctorId() {
        HttpServletRequest request = getRequest();
        if (request != null) {
            String token = request.getHeader("x-token");
            return decryptToken(token, "id");
        }
        return null;
    }

    public static String getDoctorAccount() {
        HttpServletRequest request = getRequest();
        if (request != null) {
            String token = request.getHeader("x-token");
            return decryptToken(token, "account");
        }
        return null;
    }

}
